import { BadGatewayException, Body, Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';
import { User } from 'src/decorator/user.decorator';
import { LanxiModel } from 'src/mongodb/models/lianxiModel/LanxiModel';
import { deleteUserDto, updateUserDto } from '../userApi/userDto/userDto';

@Controller('web')
export class ContactController {
    constructor(@InjectModel(LanxiModel) private readonly contact: ModelType<LanxiModel>) { }



    /* 增加 */
    @Post('addContact')
    @UseGuards(AuthGuard("jwtweb"))
    async addContact(@Body() body, @User() user) {
        let contact = []
        body.contact.forEach(element => {
            if (element) {
                contact.push({
                    contact: element,
                    createTime: Math.floor(Date.now() / 1000),
                    userid: user._id,
                    type: body.type,
                    mark: body.mark
                })
            }
        });
        try {
            await this.contact.create(contact)
            return { code: 200, message: '添加成功' }
        } catch (error) {
            return { code: 500, message: '添加失败' }
        }

    }



    /* 一键上号 */
    @Post('addContactAcc')
    @UseGuards(AuthGuard("jwtweb"))
    async addContactAcc(@Body() body, @User() user) {
        let contact = []
        body.contact.forEach(element => {
            if (element) {
                body.markArr.forEach(mark => {
                    contact.push({
                        contact: element,
                        createTime: Math.floor(Date.now() / 1000),
                        userid: user._id,
                        type: body.type,
                        mark
                    })
                })
            }
        });
        try {
            await this.contact.create(contact)
            return { code: 200, message: '上号成功' }
        } catch (error) {
            return { code: 500, message: '添加失败' }
        }

    }



    /**
    * @Description: 修改联系客服状态
    * @param id {String} 用户id
    * @param status {String} 状态
    * @return: Promise
    */
    @Post('updateContact')
    @UseGuards(AuthGuard("jwtweb"))
    async updateContact(@Body() body: updateUserDto) {
        try {
            await this.contact.updateOne({ _id: body.id }, { status: body.status })
            return { code: 200, message: '修改成功' }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
   * @Description: 删除联系客服
   * @param id {String} 用户id
   * @return: Promise
   */
    @Post('deleteContact')
    @UseGuards(AuthGuard("jwtweb"))
    async deleteContact(@Body() body: deleteUserDto) {
        try {
            await this.contact.deleteOne({ _id: body.id })
            return { code: 200, message: '删除成功' }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }

    /**
   * @Description: 批量删除客服
   * @return: Promise
   */
    @Post('deleteContactxz')
    // @UseGuards(AuthGuard("jwtweb"))
    async deleteContactxz(@Body() body) {
        try {
            try {
                await this.contact.updateMany({
                    contact: { $in: body.contact }
                }, { status: false })
                return { code: 200, message: '下号成功' }
            } catch (error) {
                return { code: 500, message: '下号失败' }
            }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
   * @Description: 删除全部联系客服
   * @return: Promise
   */
    @Post('deleteContactAll')
    @UseGuards(AuthGuard("jwtweb"))
    async deleteContactAll(@Body() body, @User() user) {
        try {
            if (user.name == 'admin') {
                await this.contact.deleteMany({ mark: body.mark })
            } else {
                const res = await this.contact.deleteMany({ userid: user._id, mark: body.mark })
                console.log(res);

            }

            return { code: 200, message: '删除成功' }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
   * @Description: 删除全部联系客服
   * @return: Promise
   */
    @Post('deleteAccAll')
    @UseGuards(AuthGuard("jwtweb"))
    async deleteAccAll(@Body() body, @User() user) {
        try {
            if (user.name == 'admin') {
                const res = await this.contact.deleteMany({ mark: { $in: body.contact } })
                if (res.deletedCount > 0) {
                    return { code: 200, message: '删除成功' }
                } else {
                    throw '删除失败'
                }

            } else {
                const res = await this.contact.deleteMany({ userid: user._id, mark: { $in: body.contact } })
                if (res.deletedCount > 0) {
                    return { code: 200, message: '删除成功' }
                } else {
                    throw '删除失败'
                }
            }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /**
  * @Description: 查询联系客服列表
  * @param pageNo {Number} 页码
  * @param pageSize {Number}  每页条数
  * @param mark {Number}  包号
  * @return: Promise
  */
    @Get('getContactList')
    @UseGuards(AuthGuard("jwtweb"))
    async getContactList(@Query() query) {
        try {
            let data: { pageNo: number | string, pageSize: number | string } = query
            if (typeof data.pageNo == 'string') {
                data.pageNo = parseInt(data.pageNo)
            }
            if (typeof data.pageSize == 'string') {
                data.pageSize = parseInt(data.pageSize)
            }
            const total = await this.contact.countDocuments({ mark: query.mark })
            const userlist = await this.contact.find({ mark: query.mark }).skip((data.pageNo - 1) * data.pageSize).limit(data.pageSize).sort({ '_id': -1 });
            return { total, data: userlist }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /**
    * @Description: 搜索用户
    * @param name {Number} 账户
    * @param mark {Number}  包号
    * @return: Promise
    */
    @Get('searchContact')
    async searchContact(@Query() query) {
        try {
            const userlist = await this.contact.find({ contact: query.name, mark: query.mark })
            return { total: userlist.length, data: userlist }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



}
